package cn.pzhuWEB.llk.controller;

import cn.pzhuWEB.llk.entity.Card;
import cn.pzhuWEB.llk.service.impl.CardServiceImpl;
import cn.pzhuWEB.llk.service.impl.UserServiceImpl;
import cn.pzhuWEB.llk.utils.GetRandomArray;
import cn.pzhuWEB.llk.entity.Grade;
import cn.pzhuWEB.llk.entity.SendCard;
import cn.pzhuWEB.llk.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;

@Controller
@CrossOrigin
public class LlkController {
    @Autowired
    UserServiceImpl userServiceImpl;
    @Autowired
    CardServiceImpl cardServiceImpl;

    @RequestMapping("/login")
    @ResponseBody
    private User login(User user, HttpSession session) {

        if (user.getStuCard() == null || user.getPassword() == null || user.getStuCard().contains("***")) {
            user.setFlag(2);//非法
        } else {
            user = userServiceImpl.login(user);
            if (user != null) {
                session.setAttribute("user", user);
                user.setFlag(1);//成功
            }
        }
        return user;
    }

    @RequestMapping("/register")
    @ResponseBody
    private User register(User user, HttpSession session) {
        if (user.getPhone().contains("***") || user.getStuName().contains("***") || user.getMajor().contains("***")) {
            user.setFlag(2);//非法
            return user;
        }
        if (userServiceImpl.findByStuCard(user.getStuCard()) == null) {
            userServiceImpl.register(user);
            session.setAttribute("user", user);
            user.setFlag(1);//注册成功
        } else {
            user.setFlag(0);//用户名已存在
        }
        return user;
    }

    @RequestMapping("/isTrue")
    @ResponseBody
    private Grade isTrue(String value1, String value2, String time, HttpSession session) {
        boolean aTrue = isTrue(value1, value2, (HashMap<?, ?>) session.getAttribute("cardMap"));
        Integer count = (Integer) session.getAttribute("count");
        HashMap<?, ?> cardMap = (HashMap<?, ?>) session.getAttribute("cardMap");
        if (aTrue) {
            if (++count == cardMap.size()) {
                long timeLong = Long.parseLong(time);
                User user = (User) session.getAttribute("user");
                String newTime = format(timeLong);
                user.setStuCompleteTime(newTime);
                //记录每次用户完成游戏的时间，4x4游戏
                if (cardMap.size()==8){
                    userServiceImpl.insetGradeFour(user);
                    String compTime = userServiceImpl.queryCompTimeFour(user);
                    if (compTime == null || compTime.compareTo(newTime) > 0) {
                        if (compTime==null){
                            userServiceImpl.insertFourRank(user);
                        }else {
                            userServiceImpl.updateUserGradeFour(user);
                        }
                        Integer gradeCount = userServiceImpl.findGradeFourByTimeRanking(user);
                        return new Grade(gradeCount);
                    } else {
                        user.setStuCompleteTime(compTime);
                        Integer gradeCount = userServiceImpl.findGradeFourByTimeRanking(user);
                        //您本次成绩****，个人最好成绩为：****，个人最高排名：***，再接再厉哦！
                        return new Grade(compTime, gradeCount);
                    }
                }else if(cardMap.size()==18){ //6x6游戏
                    userServiceImpl.insertGradeSix(user);
                    String compTime = userServiceImpl.queryCompTimeSix(user);
                    if (compTime == null || compTime.compareTo(newTime) > 0) {
                        if (compTime==null){
                            userServiceImpl.insertSixRank(user);
                        }else {
                            userServiceImpl.updateUserGradeSix(user);
                        }
                        Integer gradeCount = userServiceImpl.findGradeSixByTimeRanking(user);
                        return new Grade(gradeCount);
                    } else {
                        user.setStuCompleteTime(compTime);
                        Integer gradeCount = userServiceImpl.findGradeSixByTimeRanking(user);
                        //您本次成绩****，个人最好成绩为：****，个人最高排名：***，再接再厉哦！
                        return new Grade(compTime, gradeCount);
                    }
                }

            }
            session.setAttribute("count", count);
        }
        return new Grade(aTrue);
    }

    /**
     * 查询对应游戏的总排行榜：
     * 1：4x4
     * 2：6x6
     * 3：拼图
     * @param number
     * @return
     */
    @RequestMapping("/grade")
    @ResponseBody
    private List<User> grade(int number) {
        switch (number){
            case 1:return userServiceImpl.findFourRank();
            case 2:return userServiceImpl.findSixRank();
            default:return null;
        }
    }

    @RequestMapping("/card")
    @ResponseBody
    private ArrayList<SendCard> card(String classes, int number, HttpSession session) throws IOException {
        HashMap<String, String> map = new HashMap<>();
        ArrayList<Card> cards = cardServiceImpl.findFCardByClasses(classes);
        int[] inits = GetRandomArray.randomArray(0, cards.size() - 1, number / 2);
        ArrayList<SendCard> sendCards = new ArrayList<>();
        for (int i = 0; i < inits.length; i++) {
            String key = cards.get(inits[i]).getKey();
            String value = cards.get(inits[i]).getValue();
            SendCard sendCardKey = new SendCard(cards.get(inits[i]).getImagePath(), key);
            SendCard sendCardValue = new SendCard(cards.get(inits[i]).getImagePath(), value);
            sendCards.add(sendCardKey);
            sendCards.add(sendCardValue);
            if (map.get(key) != null) {
                map.put(value, key);
            } else {
                map.put(key, value);
            }
        }
        Collections.shuffle(sendCards);
        session.setAttribute("cardMap", map);
        session.setAttribute("count", 0);
        return sendCards;
    }

    private String format(long elapsed) {
        int minute, second, milli;
        milli = (int) (elapsed % 1000);
        elapsed = elapsed / 1000;
        second = (int) (elapsed % 60);
        elapsed = elapsed / 60;
        minute = (int) (elapsed % 60);
        return String.format("%02d:%02d %03d", minute, second, milli);
    }

    public boolean isTrue(String key, String value, HashMap<?, ?> map) {
        Object o = map.get(key);
        Object p = map.get(value);
        if (o != null && o.equals(value)) {
            return true;
        }
        return p != null && p.equals(key);
    }

}